<?php
namespace Phpcmf\Extend;

class CodeIgniter extends \CodeIgniter\CodeIgniter
{
    /**
     * 初始化程序
     */
    public function __construct(...$params)
    {
        parent::__construct(...$params);
        // 自定义函数库
        if (is_file(WEBPATH.'config/custom.php'))
        {
            require WEBPATH.'config/custom.php';
        }
        if (is_file(MYPATH.'Helper.php'))
        {
            require MYPATH.'Helper.php';
        }
        require CMSPATH.'Core/Helper.php';
    }

    /**
     * 初始化方法
     */
    public function initialize()
    {
        parent::initialize();
        \Phpcmf\Hooks::trigger('init');
    }

    /**
     * 不执行此方法
     */
    protected function bootstrapEnvironment() {

    }

    /**
     * 找不到控制器时的错误显示
     */
    protected function display404errors(\CodeIgniter\PageNotFoundException $e)
    {

        // Display 404 Errors
        $this->response->setStatusCode(404);

        ob_start();

        $heading = 'Page Not Found';
        $message = $e->getMessage() . '<br>'. FC_NOW_URL;

        // Show the 404 error page
        if (is_cli())
        {
            require COREPATH.'Views/errors/cli/error_404.php';
        }
        else
        {
            require COREPATH.'Views/errors/html/error_404.php';
        }

        $buffer = ob_get_contents();
        ob_end_clean();

        echo $buffer;
        $this->callExit(EXIT_UNKNOWN_FILE);    // Unknown file
    }
}

/**
 * 全局返回消息
 */
function dr_exit_msg($code, $msg, $data = []) {


    ob_end_clean();

    $rt = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    ];

    if (isset($_GET['callback'])) {
        // jsonp
        @header('HTTP/1.1 200 OK');
        echo ($_GET['callback'] ? $_GET['callback'] : 'callback').'('.json_encode($rt).')';
    } else if (($_GET['is_ajax'] || (defined('IS_API_AUTH_POST') && IS_API_AUTH_POST) || IS_AJAX)) {
        // json
        @header('HTTP/1.1 200 OK');
        echo json_encode($rt);
    } else {
        // html
        exit($msg);
    }
    exit;
}